package server.conn;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.sql.Date;

import server.Logger;
import server.price.PriceController;

public class PriceBroadcaster extends Thread {	
	private long SLEEP_TIME = 2000;
	private DatagramSocket socket;
	private volatile boolean running;
	private int port;
    
	/**
	 * Create a new PriceBroadcaster
	 * @param port		Port to send on
	 * @throws IOException
	 */
	public PriceBroadcaster (int port) throws IOException {
	    super("PriceBroadcasterThread");
	    this.port = port;
	    socket = new DatagramSocket(port-1);
	    Logger.getInstance().addLog("PriceBroadcaster has started on port "+(port-1), 1);
	} 
    
	/**
	 * Stop broadcasting and shutdown the thread
	 */
	public void shutdown() { running = false; }

    /**
     * Start broadcasting prices
     */
	public void run() {
    	running = true;
        while (running) {
            try {
                byte[] buf = new byte[256];

                for (String pair : PriceController.getInstance().getCurrPairs()) {
            		String dString = PriceController.getInstance().getPrice(pair).toString();
                    buf = dString.getBytes();

                    InetAddress group = InetAddress.getByName("230.0.0.1");
                    DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
                    socket.send(packet);
                }
				try {
				    sleep(SLEEP_TIME);
				} catch (InterruptedException e) { }
            } catch (IOException e) { running = false; }
        }
        socket.close();
    }
}
